#pragma once

#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <queue>
#include <string>

template <typename T>
class BlockQueue
{
public:
    bool IsFull()
    {
        return _max_cap == _block_queue.size();
    }
    bool IsEmpty()
    {
        return _block_queue.empty();
    }

public:
    BlockQueue(const int max_cap): _max_cap(max_cap)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_c_cond, nullptr);
        pthread_cond_init(&_p_cond, nullptr);
    }
    void Pop(T *out) // 消费者
    {
        pthread_mutex_lock(&_mutex);
        while (IsEmpty())
        {
            pthread_cond_wait(&_c_cond, &_mutex);
        }

        *out = _block_queue.front();
        _block_queue.pop();
        pthread_mutex_unlock(&_mutex);
        pthread_cond_signal(&_p_cond);
    }
    void Equeue(const T &in) // 生产者
    {
        pthread_mutex_lock(&_mutex);
        while (IsFull())
        {
            // 满了，在指定条件变量下阻塞等待
            pthread_cond_wait(&_p_cond, &_mutex);
        }
        // 没满||被唤醒了
        _block_queue.push(in);
        pthread_mutex_unlock(&_mutex);
        pthread_cond_signal(&_c_cond);
    }
    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_c_cond);
        pthread_cond_destroy(&_p_cond);
    }

private:
    std::queue<T> _block_queue;
    int _max_cap;

    pthread_mutex_t _mutex;

    pthread_cond_t _c_cond;
    pthread_cond_t _p_cond;
};
